<template>
    <el-dialog v-model="FromRfq" title="From RFQ" draggable width="50%"
        style="position: absolute;top:0px;left:0;right:0; height:50vh;">
        <div class="addRight bs brs pl-10 pt-10 pr-10 ">
            <div class="flex jc-sb">
                <el-select v-model="rqfValut" @input="getRfq" @change="rfqInfo" @visible-change="visibleRfq" filterable
                    placeholder="Please select an inquiry" style="width: 20%;">
                    <el-option v-for="item in rfqList" :key="item.inquiry_id" :label="item.inquiry_id"
                        :value="item.inquiry_id" />
                </el-select>
                <div>
                    <el-button type="primary" @click="New" plain>New</el-button>
                    <el-button type="primary" @click="save" plain class="add">Save</el-button>
                    <el-popconfirm title="Sure to delete?" @confirm="Delete">
                        <template #reference>
                            <el-button type="primary" plain class="del">Delete</el-button>
                        </template>
                    </el-popconfirm>
                </div>
            </div>
            <div class="mt-10 w100p">
                <el-table :data="tableData" v-loading="loading" @selection-change="row" @cell-click="table" :row-class-name="rfqList"
                    height="34.5vh" style="width: 100%">
                    <el-table-column type="selection" width="30" />
                    <el-table-column label="MODEL" min-width="160">
                        <template v-slot="model">
                            <el-select v-model="model.row.product.product_id" :disabled="model.row.item.quotation_price != ''||!powerList.inquiry.inquiry_model.Isenable" @change="changeModel" :remote-method="getModel"
                                remote @visible-change="visible" filterable placeholder="MODEL">
                                <el-option v-for="item in newModel" :key="item.id" :label="item.label" :value="item.id" />
                            </el-select>
                        </template>
                    </el-table-column>
                    <el-table-column label="BRAND" min-width="130">
                        <template v-slot="brand">
                            <el-select v-model="brand.row.brand.brand_id" :disabled="brand.row.item.quotation_price != ''||!powerList.inquiry.inquiry_brand.Isenable" :remote-method="getBrand" remote
                                @visible-change="visible" filterable placeholder="BRAND">
                                <el-option v-for="item in newBrand" :key="item.id" :label="item.label" :value="item.id" />
                            </el-select>
                        </template>
                    </el-table-column>
                    <el-table-column align="center" label="Qty" width="80">
                        <template v-slot="qty">
                            <el-input v-model="qty.row.Qty" :disabled="qty.row.item.quotation_price != ''||!powerList.inquiry.inquiry_qty.Isenable"/>
                        </template>
                    </el-table-column>
                    <!-- 售出价 -->
                    <el-table-column v-if="store.type != '3'" align="center" label="PRICE" min-width="100">
                        <template v-slot="price">
                            <el-input v-model="price.row.item.quotation_price" :disabled="!powerList.inquiry.inquiry_price.Isenable"
                                @input="inpPrice($event, price.row.item.purchase_price, price.row)" />
                        </template>
                    </el-table-column>

                    <!-- 利润 -->
                    <el-table-column v-if="store.type == '2'" align="center" label="Profit" min-width="95">
                        <template v-slot="profit">
                            <div class="flex aic">
                                <el-input v-model="profit.row.item.profit_rate" :disabled="!powerList.inquiry.inquiry_profit.Isenable"
                                    @input="newSale($event, profit.row.item.purchase_price, profit.row)" />
                                <p class="f18">%</p>
                            </div>
                        </template>
                    </el-table-column>
                    <!-- 成本价 -->
                    <el-table-column v-if="store.type != '4'" align="center" label="COST" min-width="80">
                        <template v-slot="cost">
                            <el-input v-model="cost.row.item.purchase_price" :disabled="!powerList.inquiry.inquiry_cost.Isenable"
                                @input="inpCost($event, cost.row.item.profit_rate, cost.row)" />
                        </template>
                    </el-table-column>
                    <el-table-column align="center" label="LEADING" width="120">
                        <template v-slot="leading">
                            <el-select v-model="leading.row.item.leadingtime" :disabled="!powerList.inquiry.inquiry_leading.Isenable" filterable placeholder="Select">
                                <el-option v-for="item in newLeading" :key="item.label" :label="item.label"
                                    :value="item.case" />
                            </el-select>
                        </template>
                    </el-table-column>
                    <el-table-column align="center" label="CONDITION" width="150">
                        <template v-slot="condition">
                            <el-select v-model="condition.row.item.product_condition" :disabled="!powerList.inquiry.inquiry_condition.Isenable" filterable placeholder="Select">
                                <el-option v-for="item in newCondition" :key="item.label" :label="item.label"
                                    :value="item.case" />
                            </el-select>
                        </template>
                    </el-table-column>
                    <!-- <el-table-column align="center" label="RFQ FROM" width="100">
                        <template v-slot="rfq">
                            <el-input :value="rfq.row.product.model ? rfqId : ''" disabled />
                        </template>
                    </el-table-column> -->
                </el-table>
            </div>
        </div>
    </el-dialog>
</template>

<script setup>
import { ref ,onMounted } from 'vue'
import * as $axios from '../../../../api/index'
import useBrand from '../../../../hooks/useBrand'
import useModel from '../../../../hooks/useModel'
import { ElMessage } from 'element-plus'
import { useDemoStore } from '../../../../pinia/index'
import usePower from "../../../../hooks/usePower";
const store = useDemoStore()
const { powerList } = usePower()

defineProps({
    newLeading: Array,
    newCondition: Array
})

// 加载
const loading = ref(false)

// 添加订单弹窗
const FromRfq = ref(false)
const rfq = () => {
    FromRfq.value = true
}
// 把open暴露给父组件
defineExpose({
    rfq
})


const visibleRfq = () => {
    inpOrder.value = ''  //清空输入框
    getRfq()
}

// 获取询盘列表
const rqfValut = ref('')
const rfqList = ref([])
const inpOrder = ref('')
const getRfq = (value) => {
    if (value) {
        if (value.data != null) {
            inpOrder.value += value.data
        } else if (value.data == null) {
            inpOrder.value = inpOrder.value.slice(0, -1)
        }
    }
    const data = {
        token: store.token,
        keywords: inpOrder.value,
        purchaser: store.type == 3 ? store.userId : '',
    }
    $axios.$orderGet_inquiry_by_key(data).then(res => {
        rfqList.value = res.data.data
        // console.log(rfqList.value)
    })
}


// 获取询盘信息
const tableData = ref([])
const storeValie = ref('')
const currency = ref('') //汇率
const rfqInfo = (value) => {
    loading.value = true
    storeValie.value = value || storeValie.value
    const data = {
        token: store.token,
        inquiry_id: storeValie.value
    }
    $axios.$quotationServiceQuotation(data).then(res => {
        loading.value = false
        console.log(res.data)
        tableData.value = res.data   //列表数据
        currency.value = res.data.quotation_current_rate || 1
        tableData.value.push({  //增加空白列
            "Qty": '',
            "item": {
                "quotation_price":''
            },
            "index": Math.round(Math.random() * (9000 - 100) + 100),
            "product": {

            },
            "purchase": {

            },
            "brand": {
                "brand_name": ""
            },
        })
        // console.log(order_id.value)
    })
}

onMounted(()=>{
    getModel(),
    getBrand()
})

// model
var newModel = ref([])
const getModel = (text) => {
    newModel.value = { newModel } = useModel(text)
}

// brand
var newBrand = ref([])
const getBrand = (text) => {
    newBrand.value = { newBrand } = useBrand(text)
}

// 获取利润，计算售出价
const getprofit = ref(0)
const newSale = (e, value, data) => {  //获取利润
    console.log(e, value)
    getprofit.value = (((e / 100) * (value || 0 * 1) + (value || 0) * 1) * currency.value).toFixed(2)   //计算售出价
    data.item.quotation_price = getprofit.value
}


// 获取售出价,计算利润
const newProfit = ref()  //利润
const inpPrice = (e, value, data) => {
    newProfit.value = (((e - value * 1) / value * 1 * 100) * currency.value).toFixed(2)  //计算利润比
    data.item.profit_rate = newProfit.value != 'NaN' ? newProfit.value : 0
}

// 获取成本价,计算售出价
const tmoney = ref(0)  //售出价
const inpCost = (e, value, data) => {
    tmoney.value = ((e * ((value || 0) / 100) + e * 1) * currency.value).toFixed(2)  //计算售出价
    data.item.quotation_price = tmoney.value
    // console.log(e, (value||0 )/ 100)
}

// 多选框
const id = ref([])
const random = ref([])
const row = (value) => {
    id.value = []
    random.value = []
    value.forEach(item => {
        if (item.index) {
            random.value.push(item.index)
        } else {
            id.value.push(item.item.inquiry_item_info_id)
        }
    })
}

// 删除
const Delete = () => {
    // console.log(value)
    if (id.value.length > 0 || random.value.length > 0) {
        if (id.value.length > 0) {
            const data = {
                token: store.token,
                inquiry_item_info_id: id.value
            }
            $axios.$orderDel_quotation(data).then(res => {
                if (res.Status === 0) {
                    id.value.forEach(item => {
                        const index = tableData.value.findIndex(arr => arr.item.inquiry_item_info_id == item)
                        index != -1 && tableData.value.splice(index, 1)  //删除数组里面的成员
                    })
                    ElMessage({
                        message: 'Successful preservation',
                        type: 'success',
                    })
                }
            })
        }
        if (random.value.length > 0) {
            random.value.forEach(item => {
                const index = tableData.value.findIndex(arr => arr.index == item)
                index != -1 && tableData.value.splice(index, 1)  //删除数组里面的成员
            })
        }
    } else {
        ElMessage({
            message: 'Please choose',
            type: 'warning',
        })
    }
}

// 新建
const New = () => {
    // console.log(rqfValut.value)
    if (tableData.value) {
        tableData.value = []
        for (let i = 0; i < 5; i++) {
            tableData.value.push({  //增加空白列
                "Qty": '',
                "msg": 1,
                "item": {
                    "quotation_price":''
                },
                "product": {

                },
                "purchase": {

                },
                "brand": {
                    "brand_name": ""
                },
            })
        }
    } else {
        ElMessage({
            message: 'Please select an inquiry',
            type: 'warning',
        })
    }
}


// 选择最后一个model时创建空白表单
const changeModel = () => {
    // console.log(rightList.value)
    const model = tableData.value[tableData.value.length - 1].product.model
    console.log(model)
    if (model) {
        tableData.value.push({  //增加空白列
            "Qty": '',
            "item": {
                "quotation_price":''
            },
            "index": Math.round(Math.random() * (9000 - 100) + 100),
            "product": {

            },
            "purchase": {

            },
            "brand": {
                "brand_name": ""
            },
        })
    }
}

// 保存
const save = () => {
    const quotation = ref([])
    const saveData = ref([])
    tableData.value.forEach(item => {
        if (item.product.product_id) {
            saveData.value.push(item)
        }
    });
    quotation.value = saveData.value.map(item => {
        return {
            "inquiry_item_info_id": item.inquiry_item_info_id || '',
            "quotation_price": item.item.quotation_price,
            "purchase_price": item.item.purchase_price,
            "profit_rate": item.item.profit_rate,
            "product_id": item.product.product_id,
            "leadingtime": item.item.leadingtime,
            "product_condition": item.item.product_condition,
            "brand_id": item.brand.brand_id,
            "purchaser_id": item.purchaser_id || '',
            "qty": item.Qty || 0,
        }
    })
    console.log(quotation.value)
    console.log(tableData.value[0])

    const data = {
        token: store.token,
        inquiry_id: storeValie.value,
        quotation: quotation.value
    }
    if (tableData.value[0].msg == 1) { //新建
        $axios.$orderNew_quotation_fun(data).then(res => {
            if (res.Status === 0) {
                FromRfq.value = false
                emits('update')
                ElMessage({
                    message: 'Successful preservation',
                    type: 'success',
                })
            }
            // console.log(res)
        })
    } else {
        $axios.$orderSet_quotation(data).then(res => {
            if (res.Status === 0) {
                tableData.value[0].msg == 1 || rfqInfo()
                ElMessage({
                    message: 'Successful preservation',
                    type: 'success',
                })
            }
            // console.log(res)
        })
    }
}

const emits = defineEmits(['update'])
</script>

<style lang="less" scoped>
.add.el-button.is-plain {
    border: 1px solid #7da3f3;
    color: #7da3f3;
    background-color: #ecf5ff;
}

.el-button.is-plain {
    border: 1px solid #6193D2;
    color: #6193D2;
    background-color: #fff;
}

.del.el-button.is-plain {
    border: 1px solid #6193D2;
    color: #fff;
    background-color: #6393D4;
}
</style>